<template>
  <div class="login">
    <!-- 导航栏 -->
    <van-nav-bar
      title="登录"
    />

    <!-- 登录表单 -->
    <!--
      ValidationObserver 组件会渲染成一个 form 表单
      可以通过 ref 调用这个组件的方法：validate 来进行 js 验证
     -->
    <ValidationObserver tag="form" ref="loginForm">
      <!--
        把需要验证的字段使用 ValidationProvider 包裹起来
        在其上面配置对应的验证规则等信息
       -->
      <ValidationProvider tag="div" name="手机号" rules="required|phone" v-slot="{ errors }">
        <van-field
          v-model="user.mobile"
          clearable
          label="手机号"
          placeholder="请输入手机号"
          left-icon="phone-o"
          :error-message="errors[0]"
        />
      </ValidationProvider>
      <ValidationProvider tag="div" name="验证码" rules="required" v-slot="{ errors }">
        <van-field
          v-model="user.code"
          center
          clearable
          label=" 验证码"
          placeholder="请输入短信验证码"
          left-icon="chat-o"
          :error-message="errors[0]"
          >
          <van-button slot="button" size="small" type="primary">发送验证码</van-button>
        </van-field>

      </ValidationProvider>
    </ValidationObserver>

     <!-- 登录按钮 -->
    <div class="login-wrap">
       <van-button type="info"
       :loading="isLoginLoading"
       loading-text="加载中..."
       @click="onLogin"
       >
       登录</van-button>
    </div>

  </div>
</template>

<script>
import { login } from '@/api/user'

export default {
  name: 'LoginIndex',
  data () {
    return {
      user: {
        mobile: '13678523690',
        code: '246810'
      },
      isLoginLoading: false
    }
  },

  methods: {
    async onLogin () {
      // this.isLoginLoading = true
      try {
        // 表单验证
        const isValid = await this.$refs.loginForm.validate()

        // 验证失败，则什么都不做
        if (!isValid) {
          return
        }
        // 验证通过，提交表单
        this.isLoginLoading = true

        const res = await login(this.user)

        this.$store.commit('setUser', res.data.data)

        this.$toast.success('登录成功')
        this.$router.push('/')
      } catch (err) {
        if (err.response && err.response.status === 400) {
          this.$toast.fail('登录失败手机号或验证码错误')
        }
      }
      this.isLoginLoading = false
      // 获取表单数据
      // 发送请求
    }
  }
}
</script>

<style lang="less" scoped>
  .login {
    .login-wrap {
      padding: 20px;
      .van-button {
        width: 100%;
        border-radius: 5px;
      }
    }
  }
</style>
